<template>
  <div class="page-container">
    <div class="card-title" v-show="showSearch">
      <el-form size="small" label-width="68px" :model="queryParams" ref="queryForm">
        <el-row :gutter="48">
          <el-col :md="6" :sm="24">
            <el-form-item label="分类名称">
              <el-input v-model="queryParams.name" class="search-item" placeholder="请输入博客分类名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="可见类型">
              <el-select v-model="queryParams.visibility" placeholder="请选择分类可见类型" class="search-item" clearable>
                <el-option v-for="dict in dict.type.blog_visible_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <!-- 创建时间 -->
            <el-form-item label="创建时间">
              <el-date-picker v-model="queryParams.dataRange" class="search-item" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <div class="search-content">
            <!-- 搜索按钮 -->
            <el-form-item class="search-button">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
              <el-button type="text" :icon="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" class="advanced-button" @click="toggleAdvanced"> {{ advanced ? '关闭' : '展开' }}</el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <div class="card">
      <el-row :gutter="10" class="button-container">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini" plain>新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" plain :disabled="single" @click="handleUpdate">编辑</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" plain :disabled="multiple" @click="handleDelete" :loading="buttonLoading">删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" :columns="columns" @getTableData="getTableData"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" element-loading-text="正在加载表格数据" :data="tableData" @selection-change="handleSelectionChange" border>
        <template slot="empty">
          <el-empty :image-size="200"></el-empty>
        </template>
        <el-table-column type="selection" width="50" align="center" />
        <!-- 分类名称 -->
        <el-table-column prop="name" label="分类名称" align="center" v-if="columns[0].visible"></el-table-column>
        <!-- 分类描述 -->
        <el-table-column prop="description" label="分类描述" align="center" v-if="columns[1].visible"></el-table-column>
        <!-- 分类图标 -->
        <el-table-column prop="icon" label="分类图标" align="center" v-if="columns[2].visible">
          <template slot-scope="scope">
            <svg-icon :icon="scope.row.icon"></svg-icon>
          </template>
        </el-table-column>
        <!-- 可见类型：0 自己可见 1 全部可见 -->
        <el-table-column prop="visibility" label="可见类型" align="center" v-if="columns[3].visible">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.visibility === '1'">全部可见</el-tag>
            <el-tag type="primary" v-else-if="scope.row.visibility === '0'">自己可见</el-tag>
          </template>
        </el-table-column>
        <!-- 文章数量 -->
        <el-table-column prop="count" label="文章数量" align="center" v-if="columns[4].visible" sortable></el-table-column>
        <el-table-column prop="sort" label="分类排序" align="center" v-if="columns[5].visible" sortable>
          <template slot-scope="scope">
            <el-tag type="warning">{{ scope.row.sort }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" v-if="columns[6].visible">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <pagination
        :background="false"
        :total="total"
        :page.sync="queryParams.currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableData"
      />
    </div>

    <!-- 分类信息对话框 -->
    <el-dialog
      :title="categoryTitle"
      width="500px"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :visible="categoryVisible"
      :before-close="handleClose">
      <div class="category-wrapper" v-loading="categoryLoading" element-loading-text="正在加载分类信息">
        <el-form ref="categoryForm" :model="formData" :rules="rules" label-width="80px" label-position="right">
          <el-row :gutter="15">
            <!-- 分类名称 -->
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入分类名称" clearable></el-input>
            </el-form-item>
            <!-- 分类描述 -->
            <el-form-item label="分类描述" prop="description">
              <el-input v-model="formData.description" placeholder="请输入分类描述" clearable></el-input>
            </el-form-item>
            <!-- 分类图标 -->
            <el-form-item label="分类图标" prop="icon">
              <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                  <IconSelect ref="iconSelect" @selectIcon="selectIcon" :active-icon="formData.icon" />
                  <el-input slot="reference" v-model="formData.icon" placeholder="点击选择图标" readonly>
                    <svg-icon v-if="formData.icon" slot="prefix" :icon="formData.icon" style="width: 25px;"/>
                    <i v-else slot="prefix" class="el-icon-search el-input__icon"></i>
                  </el-input>
                </el-popover>
            </el-form-item>
            <el-form-item label="分类排序" prop="sort">
              <el-input-number v-model="formData.sort" controls-position="right" :min="0" />
            </el-form-item>
            <!-- 可见类型：0 自己可见 1 全部可见 -->
            <el-form-item label="可见类型" prop="visibility">
              <el-radio-group v-model="formData.visibility">
                <el-radio v-for="dict in dict.type.blog_visible_type" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
              </el-form-item>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="danger" :loading="buttonLoading" @click="handleClose()" size="small" icon="el-icon-error"> 取消 </el-button>
        <el-button type="success" :loading="buttonLoading" @click="submitForm()" size="small" icon="el-icon-success"> 保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '../../../components/Pagination/index.vue'
import RightToolbar from '../../../components/RightToolbar/index.vue'
import IconSelect from '../../../components/IconSelect/index'
import { listBlogCategorys, saveBlogCategory, getBlogCategoryById, deleteBlogCategory } from '../../../api/blog/blog-category'

export default {
  name: 'Category',

  dicts: ['blog_visible_type'],

  components: { Pagination, RightToolbar, IconSelect },

  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 是否展示搜索内容
      showSearch: true,
      // 数据总条数
      total: 0,
      // 分类对话框是否显示
      categoryVisible: false,
      // 数据表格等待框
      loading: false,
      // 查询参数
      queryParams: {
        // 页数
        currentPage: 1,
        // 页面大小
        pageSize: 10,
        // 分类名称
        name: undefined,
        // 分类类型
        visibility: undefined,
        // 时间范围
        dataRange: []
      },
      // 分类表单对象
      formData: {
        // 分类名称
        name: undefined,
        // 分类描述
        description: undefined,
        // 分类排序
        sort: 0,
        // 分类图标
        icon: undefined,
        // 可见类型：0 自己可见 1 全部可见
        visibility: '1'
      },
      // 分类表单校验规则
      rules: {
        // 分类名称
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        // 分类类型：0 自己可见 1 全部可见
        visibility: [{ required: true, message: '请选择博客分类访问类型', trigger: 'blur' }]
      },
      // 分类对话框等待框
      categoryLoading: false,
      // 对话框按钮等待框
      buttonLoading: false,
      // 列信息
      columns: [
        // 分类名称
        { key: 0, label: '分类名称', visible: true },
        // 分类描述
        { key: 1, label: '分类描述', visible: true },
        // 分类图标
        { key: 2, label: '分类图标', visible: true },
        // 分类类型：0 所有人不可见 1 所有人可见 2 仅自己可见
        { key: 3, label: '分类类型', visible: true },
        // 文章数量
        { key: 4, label: '文章数量', visible: true },
        // 分类排序
        { key: 5, label: '分类排序', visible: true },
        { key: 6, label: '创建时间', visible: true }
      ],
      // 表格数据
      tableData: [],
      // 表头选中的数据
      ids: [],
      // 多数据禁用
      single: true,
      // 单数据禁用
      multiple: true,
      // 对话框标题
      categoryTitle: ''
    }
  },

  mounted () {
    // 查询表格数据
    this.getTableData()
  },

  methods: {
    // 获取表格数据
    getTableData () {
      // 开启加载框
      this.loading = true
      listBlogCategorys(this.queryParams).then((res) => {
        // 赋值数据参数
        this.tableData = res.list
        this.total = res.total
        // 关闭等待框
        this.loading = false
      }).catch(() => {
        // 确保加载框可以关闭
        this.loading = false
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 点击查询按钮
    handleQuery () {
      this.queryParams.currentPage = 1
      this.getTableData()
    },
    // 点击重置按钮
    handleReset () {
      // 分类名称
      this.queryParams.name = ''
      // 分类类型：0 自己可见 1 全部可见
      this.queryParams.visibility = undefined
      this.queryParams.dataRange = []
    },
    // 打开分类信息对话框
    handleOpen () {
      // 清除表单数据
      this.reset()
      this.categoryVisible = true
    },
    // 关闭分类对话框表单
    handleClose () {
      this.reset()
      this.categoryVisible = false
    },
    // 点击新增按钮
    handleAdd () {
      this.categoryTitle = '新增分类'
      this.handleOpen()
    },
    // 点击编辑按钮
    handleUpdate (row) {
      // 修改对话框标题
      this.categoryTitle = '更新分类'
      // 获取到传来的ID
      const categoryId = row.id || this.ids
      // 打开加载框
      this.categoryLoading = true
      // 根据分类ID获取对应的数据
      getBlogCategoryById(categoryId).then((res) => {
        // 赋值当前的分类数据
        this.formData = res
        // 打开编辑分类对话框
        this.categoryVisible = true
        // 关闭加载框
        this.categoryLoading = false
      })
    },
    // 点击删除事件
    handleDelete (row) {
      const that = this
      let categoryIds = []
      if (row.id) {
        categoryIds.push(row.id)
      } else {
        categoryIds = this.ids
      }
      this.$confirm('是否确认删除选中的分类数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.buttonLoading = true
        that.loading = true
        deleteBlogCategory(categoryIds).then((res) => {
          that.buttonLoading = false
          that.$message.success('删除成功')
          // 刷新数据
          that.getTableData()
        }).catch(() => {
          // 确保加载框会关闭
          that.buttonLoading = false
          that.loading = false
        })
      }).catch(() => {})
    },
    // 提交表单
    submitForm () {
      const that = this
      this.$refs.categoryForm.validate(valid => {
        // 校验未通过则直接返回
        if (!valid) return
        // 开启加载框
        that.buttonLoading = true
        that.categoryLoading = true
        // 提交表单
        saveBlogCategory(that.formData).then((res) => {
          // 根据是否存在ID输出对应消息
          if (that.formData.id) {
            // 输出更新成功信息
            that.$message.success('分类信息更新成功')
          } else {
            // 输出添加成功消息
            that.$message.success('分类添加成功')
          }
          // 刷新表单数据并关闭对话框
          that.handleClose()
          // 刷新分类数据
          that.getTableData()
          // 关闭加载框
          that.buttonLoading = false
          that.categoryLoading = false
        }).catch(() => {
          // 关闭加载框
          that.buttonLoading = false
          that.categoryLoading = false
        })
      })
    },
    // 重置表单
    reset () {
      // 清除校验条件
      this.formData = {
        // 分类ID
        id: undefined,
        // 分类名称
        name: undefined,
        // 分类排序
        sort: 0,
        // 分类图标
        icon: undefined,
        // 可见类型：0 自己可见 1 全部可见
        visibility: '1'
      }
      // 清除表单校验
      this.resetForm('categoryForm')
    },
    // 多选框
    handleSelectionChange (selection) {
      // 获取当前选中数组的ID
      this.ids = selection.map(item => item.id)
      // 表头的编辑是否可以点击
      this.single = selection.length !== 1
      // 表头的删除是否可以点击
      this.multiple = !selection.length
    },
    // 选择图标
    selectIcon (name) {
      this.formData.icon = name
    }
  }
}

</script>

<style lang="scss" scoped>
.category-wrapper {
  padding: 10px 30px;
}
.cover {
  position: relative;
  .el-image {
    border-radius: 5px;
  }
  .el-button {
    color: #fff;
  }
}
.cover-remove {
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100% - 14px);
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #00000080;
  border-radius: 5px;
  opacity: 0;
  transition: opacity 0.3s cubic-bezier(0.55, 0, 0.1, 1);
}
.cover:hover .cover-remove {
  opacity: 1;
}
</style>
